#coding=utf-8
import os
import datetime
import time
import sys
import glob
from chardet.universaldetector import UniversalDetector

## version 1.0 没有考虑已经分配的报警编号
## version 2.0 考虑已经分配的报警编号，先获取分配的最大报警号

##　用来获取Nrp代码中的日志函数，并解析出AlarmList

ALarmList = {"fatalLog" : 0, 
"errorLog" : 0,
"warningLog" : 0}

##ALarmList = {"fatalLog" : 0, 
##"errorLog" : 0,
##"warningLog" : 0,
##"infoLog" : 0,
##"debugLog" : 0,
##"traceLog" : 0,
##"default": 0}

gCurFileName = ""
gCurLine = 0

def GetEncode( filename ):
	size = os.path.getsize(filename)
	print(size)

	try:  
		f=open(filename,'rb')
		b= b' '
		b+=f.read(int(size))
		u=UniversalDetector()
		u.reset()
		u.feed(b)
		u.close()
		f.seek(0)
		b=f.read()
		f.close()
		return u.result['encoding']
	except IOError: 
		print ("GetEncode Error: " )
				
## 遍历文件夹
def getCurrFileList(dir, suffix=''):
	'''Get all file list with specified suffix under current level folder
	Input:  
		dir     :   Current folder
		suffix  :   default to blank, means select all files.
	Output:
		File list
	'''
	if suffix=='':   
		files=glob.glob(dir,recursive=True)
	else:
		files=glob.glob(dir+suffix,recursive=True)
	flist=[]    
	for f in files:
		if os.path.isfile(f) and os.path.splitext(f)[-1] == ".cpp":
			flist.append(os.path.join(os.getcwd(), f))
	return flist
	
## void Log_Add(std::wstring sLog, logLevel _level,bool Osc, int AlarmCode),
## Log_Add(logStr, errorLog, true);
## 全部从1开始
def SetLogFunction( LineStr, fatalFile, errorFile,warningFile ):
	#print(LineStr)
	if ( LineStr.find('Log_Add') == -1 ):
		return False,""
			
	#if(LineStr.count("(") > 1):  ## 不解析复杂的格式
	#	print(LineStr)
	#	return False,""
		
	if(LineStr.count(",") < 1):  ## 没有指定日志级别，代表用默认级别，不考虑写入AlarmList
		#print(LineStr)
		return False,""
		
	##NoParentheses = (LineStr.replace(' ','')).split(");")
	NoParentheses = LineStr.split(");")
	if(len(NoParentheses) < 1):
		print(LineStr)
		return False,""
	
	splitStr = NoParentheses[0].split(",")
			
	if(len(splitStr) == 2):
		keyName = splitStr[1].replace(' ','')
		print("1", keyName)
		if keyName in ALarmList:
			ALarmList[keyName] += 1
			retStr = splitStr[0] +", "+ splitStr[1]+", false, "+str(ALarmList[keyName])+");\n"
			if not WriteLog(splitStr, ALarmList[keyName], fatalFile, errorFile,warningFile):
				return False,retStr
			return True,retStr
			
	if(len(splitStr) == 3):
		keyName = splitStr[1].replace(' ','')
		print("2", keyName)
		if keyName in ALarmList:
			ALarmList[keyName] += 1
			retStr = splitStr[0]  +", "+ splitStr[1]+", "+ splitStr[2]+", "+str(ALarmList[keyName])+");\n"
			if not WriteLog(splitStr, ALarmList[keyName], fatalFile, errorFile,warningFile):
				return False,retStr			
			return True,retStr
			
	return False,""
	
def GetLogFunction( LineStr ):
	#print(LineStr)
	if ( LineStr.find('Log_Add') == -1 ):
		return True
			
	#if(LineStr.count("(") > 1):  ## 不解析复杂的格式
	#	print(LineStr)
	#	return False,""
		
	if(LineStr.count(",") < 1):  ## 没有指定日志级别，代表用默认级别，不考虑写入AlarmList
		#print(LineStr)
		return False
		
	##NoParentheses = (LineStr.replace(' ','')).split(");")
	NoParentheses = LineStr.split(");")
	if(len(NoParentheses) < 1):
		print(LineStr)
		return False
	
	splitStr = NoParentheses[0].split(",")						
	if(len(splitStr) == 4):
		keyName = splitStr[1].replace(' ','')
		print("2", keyName)
		if keyName in ALarmList:
			if(int(splitStr[3]) > ALarmList[keyName]):
				ALarmList[keyName] = int(splitStr[3])
			retStr = splitStr[0]  +", "+ splitStr[1]+", "+ splitStr[2]+", "+str(ALarmList[keyName])+");"
			print(retStr)
			return True
			
	return True
	
	
def WriteLog(splitStr, index, fatalFile, errorFile,warningFile):
	if(len(splitStr)<2):
		return False

	tmpStr = "Log_Add("
			
	if(splitStr[1].replace(' ','') == "fatalLog"):
		fatalFile.write(gCurFileName+";"+str(gCurLine)+";"+ splitStr[0][(splitStr[0].find(tmpStr)+len(tmpStr)):]+";"+splitStr[1].replace(' ','')+";"+str(index)+"\n")
		return True
	elif(splitStr[1].replace(' ','') == "errorLog"):
		errorFile.write(gCurFileName+";"+str(gCurLine)+";"+ splitStr[0][(splitStr[0].find(tmpStr)+len(tmpStr)):]+";"+splitStr[1].replace(' ','')+";"+str(index)+"\n")
		return True
	elif(splitStr[1].replace(' ','') == "warningLog"):
		warningFile.write(gCurFileName+";"+str(gCurLine)+";"+ splitStr[0][(splitStr[0].find(tmpStr)+len(tmpStr)):]+";"+splitStr[1].replace(' ','')+";"+str(index)+"\n")
		return True
			
if __name__ == '__main__':
	PathStr = "D:/awei/project/HKC/HKC/source/Nrp/src-/**"
	
	fileList = getCurrFileList(PathStr)
	for file in fileList:
		gCurFileName = file
		fileEncoding = GetEncode( gCurFileName )
		print(gCurFileName, fileEncoding)
		with open(gCurFileName, 'r+', encoding=fileEncoding) as f:
			lineList = f.readlines()
					
			gCurLine = 0		
			while(gCurLine < len(lineList)):
				GetLogFunction(lineList[gCurLine])
				gCurLine += 1

	for key,value in ALarmList.items():
		print(key, value, ";")

	print(ALarmList.keys())
	with open('D:/fatalLog.txt', 'w+', encoding='utf-8') as fatalFile:
			with open('D:/errorLog.txt', 'w+', encoding='utf-8') as errorFile:
				with open('D:/warningLog.txt', 'w+', encoding='utf-8') as warningFile:
					
					for file in fileList:
						gCurFileName = file
						fileEncoding = GetEncode( gCurFileName )
						print(gCurFileName, fileEncoding)
						with open(gCurFileName, 'r+', encoding=fileEncoding) as f:
							lineList = f.readlines()
									
							gCurLine = 0		
							while(gCurLine < len(lineList)):
								isTrue,getStr = SetLogFunction(lineList[gCurLine], fatalFile, errorFile,warningFile)
								if(isTrue):
									lineList[gCurLine] = getStr
									print(getStr)
								gCurLine += 1
								
							gCurLine = 0
							f.seek(0)
							while(gCurLine < len(lineList)):
								f.write(lineList[gCurLine])
								gCurLine += 1
								
							##else:
							##	print(line)
	print("_________end_________")
			
